var $table = $('#table');
var $userTalbe = $("#userTable");
var treeObj = null;
var URI_LIST = "/sec/role/list";
var URI_CREATE = "/sec/role/create";
var URI_UPDATE = "/sec/role/update/";
var URI_DEL = "/sec/role/delete/";
var createFrom = "#SecRolecreateForm";
var updateForm = "#SecRoleupdateForm";
var USER_URI_LIST = "/sec/role/user";
var createValidation = null;
var updateValidation = null;
var fieldCloumns = [
    {field: 'ck', checkbox: true},
    {field: 'roleName', title: '角色名称'},
    {field: 'roleDesc', title: '角色描述'},
    {field: 'userCount', title: '人数'},
    {field: 'roleState', title: '角色状态', formatter: 'roleStateFormatter'},
    {field: 'rid', title: '操作', align: 'center', formatter: 'actionFormatter', events: 'actionEvents', clickToSelect: false}
]
var userfieldCloumns = [
    {field: 'loginName', title: '登录名'},
    {field: 'nickName', title: '昵称'},
    {field: 'mobile', title: '手机号'},
    {field: 'email', title: '邮箱'},
    {field: 'useState', title: '是否禁用', formatter: 'roleStateFormatter'}
]
var csrfParameter = $("meta[name='_csrf_parameter']").attr("content");
var csrfHeader = $("meta[name='_csrf_header']").attr("content");
var csrfToken = $("meta[name='_csrf']").attr("content");
var headers = {};
headers[csrfHeader] = csrfToken;

function roleStateFormatter(value, index, row) {
    if (value == 1) {
        return "正常";
    }
    if (value == 0) {
        return "禁用";
    }
    return "-";
}

function initValidate(formId) {
    var validator = $(formId).validate({
        rules: {
            roleName: {required: true, maxlength: 100},
            roleDesc: {required: true, maxlength: 200},
            roleState: {required: true, maxlength: 2}
        }
    });
    return validator;
}

var idField = "rid";
$(function () {
    $table.bootstrapTable({
        url: URI_LIST,
        idField: idField,
        uniqueId: idField,
        toolbar: '#toolbar',
        detailView: false,
        columns: fieldCloumns
    });
    $userTalbe.bootstrapTable({
        idField: "uid",
        detailView: false,
        columns: userfieldCloumns
    });
    initTree();
});

// 格式化操作按钮
function actionFormatter(value, row, index) {
    return [
        '<a class="update" href="javascript:;" onclick="updateAction(' + value + ')" data-toggle="tooltip" title="Edit"><i class="glyphicon glyphicon-edit"></i></a>　',
        '<a class="delete" href="javascript:;" onclick="deleteAction(' + value + ')" data-toggle="tooltip" title="Remove"><i class="glyphicon glyphicon-remove"></i></a>　',
        '<a class="delete" href="javascript:;" onclick="grantAction(' + value + ')" data-toggle="tooltip" title="Remove"><i class="fa fa-shield"></i></a>'
    ].join('');
}

// 新增
var createDialog;

function createAction() {

    createDialog = $.dialog({
        animationSpeed: 300,
        title: '新增',
        columnClass: 'col-md-10',
        content: 'url:' + URI_CREATE + ".html",
        onContentReady: function () {
            initMaterialInput();
            createValidation = initValidate(createFrom)
            $(createFrom).ajaxForm({
                target: '#btn-SecRole-submit',   // target element(s) to be updated with server response
                dataType: 'json',
                url: URI_CREATE,
                beforeSubmit: function (formData, jqForm, options) {
                    return createValidation.valid();
                },
                success: function (result, statusText, xhr, $form) {
                    if (result.code != "0000") {
                        $.confirm({
                            theme: 'dark',
                            animation: 'rotateX',
                            closeAnimation: 'rotateX',
                            title: false,
                            content: result.data.errorMsg || result.desc,
                            buttons: {
                                confirm: {
                                    text: '确认',
                                    btnClass: 'waves-effect waves-button waves-light'
                                }
                            }
                        });
                    } else {
                        createDialog.close();
                        $table.bootstrapTable('refresh');
                    }
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    $.confirm({
                        theme: 'dark',
                        animation: 'rotateX',
                        closeAnimation: 'rotateX',
                        title: false,
                        content: textStatus,
                        buttons: {
                            confirm: {
                                text: '确认',
                                btnClass: 'waves-effect waves-button waves-light'
                            }
                        }
                    });
                }
            });
        }
    });
}

// 编辑
var updateDialog;

function updateAction(value) {
    var rows = []
    if (value) {
        rows.push($table.bootstrapTable('getRowByUniqueId', value));
    } else {
        rows = $table.bootstrapTable('getSelections');
    }
    if (rows.length != 1) {
        $.confirm({
            title: false,
            content: '请选择一条记录！',
            autoClose: 'cancel|3000',
            backgroundDismiss: true,
            buttons: {
                cancel: {
                    text: '取消',
                    btnClass: 'waves-effect waves-button'
                }
            }
        });
    } else {
        updateDialog = $.dialog({
            animationSpeed: 300,
            title: '编辑',
            columnClass: 'col-md-10',
            content: 'url:' + URI_UPDATE + rows[0].rid + ".html",
            onContentReady: function () {
                initMaterialInput();
                updateValidation = initValidate(updateForm)
                $(updateForm).ajaxForm({
                    target: '#btn-SecRole-update',   // target element(s) to be updated with server response
                    dataType: 'json',
                    url: URI_UPDATE + rows[0].rid,
                    beforeSubmit: function (formData, jqForm, options) {
                        return updateValidation.valid();
                    },
                    success: function (result, statusText, xhr, $form) {
                        if (result.code != "0000") {
                            $.confirm({
                                theme: 'dark',
                                animation: 'rotateX',
                                closeAnimation: 'rotateX',
                                title: false,
                                content: result.data.errorMsg || result.desc,
                                buttons: {
                                    confirm: {
                                        text: '确认',
                                        btnClass: 'waves-effect waves-button waves-light'
                                    }
                                }
                            });
                        } else {
                            updateDialog.close();
                            $table.bootstrapTable('refresh');
                        }
                    },
                    error: function (XMLHttpRequest, textStatus, errorThrown) {
                        $.confirm({
                            theme: 'dark',
                            animation: 'rotateX',
                            closeAnimation: 'rotateX',
                            title: false,
                            content: textStatus,
                            buttons: {
                                confirm: {
                                    text: '确认',
                                    btnClass: 'waves-effect waves-button waves-light'
                                }
                            }
                        });
                    }
                });
            }
        });
    }
}

// 删除
var deleteDialog;

function deleteAction(value) {
    var rows = []
    if (value) {
        rows.push($table.bootstrapTable('getRowByUniqueId', value));
    } else {
        rows = $table.bootstrapTable('getSelections');
    }
    if (rows.length == 0) {
        $.confirm({
            title: false,
            content: '请至少选择一条记录！',
            autoClose: 'cancel|3000',
            backgroundDismiss: true,
            buttons: {
                cancel: {
                    text: '取消',
                    btnClass: 'waves-effect waves-button'
                }
            }
        });
    } else {
        deleteDialog = $.confirm({
            type: 'red',
            animationSpeed: 300,
            title: false,
            content: '确认删除该记录吗？',
            buttons: {
                confirm: {
                    text: '确认',
                    btnClass: 'waves-effect waves-button',
                    action: function () {
                        var ids = new Array();
                        for (var i in rows) {
                            ids.push(rows[i].rid);
                        }
                        $.ajax({
                            type: 'get',
                            url: URI_DEL + ids.join("-"),
                            success: function (result) {
                                if (result.code != "0000") {
                                    $.confirm({
                                        theme: 'dark',
                                        animation: 'rotateX',
                                        closeAnimation: 'rotateX',
                                        title: false,
                                        content: result.desc,
                                        buttons: {
                                            confirm: {
                                                text: '确认',
                                                btnClass: 'waves-effect waves-button waves-light'
                                            }
                                        }
                                    });
                                } else {
                                    deleteDialog.close();
                                    $table.bootstrapTable('refresh');
                                }
                            },
                            error: function (XMLHttpRequest, textStatus, errorThrown) {
                                $.confirm({
                                    theme: 'dark',
                                    animation: 'rotateX',
                                    closeAnimation: 'rotateX',
                                    title: false,
                                    content: textStatus,
                                    buttons: {
                                        confirm: {
                                            text: '确认',
                                            btnClass: 'waves-effect waves-button waves-light'
                                        }
                                    }
                                });
                            }
                        });
                    }
                },
                cancel: {
                    text: '取消',
                    btnClass: 'waves-effect waves-button'
                }
            }
        });
    }
}

//授权处理
function grantAction(value) {
    var rows = [];
    if (value) {
        rows.push($table.bootstrapTable('getRowByUniqueId', value));
    } else {
        rows = $table.bootstrapTable('getSelections');
    }
    treeObj.checkAllNodes(false);
    if (rows.length == 0) {
        $.confirm({
            title: false,
            content: '请至少选择一条记录！',
            autoClose: 'cancel|3000',
            backgroundDismiss: true,
            buttons: {
                cancel: {
                    text: '取消',
                    btnClass: 'waves-effect waves-button'
                }
            }
        });
    } else {
        $("#needRid").val(rows[0].rid)
        $.getJSON("/sec/role/hasPermission?id=" + rows[0].rid, function (data) {
            if (data.code == "0000") {
                var ids = data.data;
                for (var i = 0; i < ids.length; i++) {
                    treeObj.checkNode(treeObj.getNodeByParam("permissionId", ids[i]), true, false);
                }
                $("#grantRoleModal").modal("show");
            } else {
                $.confirm({
                    theme: 'dark',
                    animation: 'rotateX',
                    closeAnimation: 'rotateX',
                    title: false,
                    content: data.desc,
                    buttons: {
                        confirm: {
                            text: '确认',
                            btnClass: 'waves-effect waves-button waves-light'
                        }
                    }
                });
            }
        })
    }
}

function grant() {
    var nodes = treeObj.getCheckedNodes(true);
    var rows = $table.bootstrapTable("getSelections");
    if (nodes != null && nodes.length > 0) {
        var ids = new Array();
        for (var i in nodes) {
            ids.push(nodes[i].permissionId);
        }
        $.ajax({
            url: "/sec/role/grant",
            headers: headers,
            type: "post",
            data: "rid=" + $("#needRid").val() + "&ids=" + ids.join("-"),
            success: function (result) {
                if (result.code != "0000") {
                    $.confirm({
                        theme: 'dark',
                        animation: 'rotateX',
                        closeAnimation: 'rotateX',
                        title: false,
                        content: result.desc,
                        buttons: {
                            confirm: {
                                text: '确认',
                                btnClass: 'waves-effect waves-button waves-light'
                            }
                        }
                    });
                } else {
                    $("#grantRoleModal").modal("hide");
                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                $.confirm({
                    theme: 'dark',
                    animation: 'rotateX',
                    closeAnimation: 'rotateX',
                    title: false,
                    content: textStatus,
                    buttons: {
                        confirm: {
                            text: '确认',
                            btnClass: 'waves-effect waves-button waves-light'
                        }
                    }
                });
            }
        });
    } else {
        $.ajax({
            url: "/sec/role/grant",
            headers: headers,
            type: "post",
            data: "rid=" + $("#needRid").val(),
            success: function (result) {
                if (result.code != "0000") {
                    $.confirm({
                        theme: 'dark',
                        animation: 'rotateX',
                        closeAnimation: 'rotateX',
                        title: false,
                        content: result.desc,
                        buttons: {
                            confirm: {
                                text: '确认',
                                btnClass: 'waves-effect waves-button waves-light'
                            }
                        }
                    });
                } else {
                    $("#grantRoleModal").modal("hide");
                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                $.confirm({
                    theme: 'dark',
                    animation: 'rotateX',
                    closeAnimation: 'rotateX',
                    title: false,
                    content: textStatus,
                    buttons: {
                        confirm: {
                            text: '确认',
                            btnClass: 'waves-effect waves-button waves-light'
                        }
                    }
                });
            }
        });
    }
}

function initTree() {
    var setting = {
        check: {
            enable: true
        },
        view: {
            dblClickExpand: false,
            showLine: true,
            selectedMulti: false
        },
        async: {
            dataType: "json",
            enable: true,
            type: "get",
            url: "/sec/role/permission",
            dataFilter: function (treeId, parentNode, responseData) {
                return responseData;
            }
        },
        data: {
            key: {
                name: "name"
            },
            simpleData: {
                enable: true,
                idKey: "permissionId",
                pIdKey: "pid",
                rootPId: "0"
            }
        },
        callback: {
            onClick: function (event, treeId, treeNode, treeFlag) {
                treeObj.checkNode(treeNode, !treeNode.checked, false);
            }
        }
    };
    var t = $("#authTree");
    t = $.fn.zTree.init(t, setting);
    treeObj = t;
}

function roleUserAction(value) {
    var rows = [];
    if (value) {
        rows.push($table.bootstrapTable('getRowByUniqueId', value));
    } else {
        rows = $table.bootstrapTable('getSelections');
    }
    if (rows.length == 0) {
        $.confirm({
            title: false,
            content: '请至少选择一条记录！',
            autoClose: 'cancel|3000',
            backgroundDismiss: true,
            buttons: {
                cancel: {
                    text: '取消',
                    btnClass: 'waves-effect waves-button'
                }
            }
        });
    } else {

        $userTalbe.bootstrapTable("refresh", {
            url: USER_URI_LIST + "?rid=" + rows[0].rid,
        });
        $("#userOfRoleModal").modal("show");
    }
}

function initRoleAction() {
    $.ajax({
        type: 'post',
        url: "/sec/role/initRole",
        success: function (result) {
            if (result.code != "0000") {
            } else {
                showMessage("重载成功")
            }
        }
    });
}